package com.xxonehjh.demo.spring.transaction.service;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionSynchronizationAdapter;
import org.springframework.transaction.support.TransactionSynchronizationManager;
import org.springframework.transaction.support.TransactionTemplate;

/**
 * @author huangjh
 * @date 2021-6-17 17:15:43
 */
@Service
public class OrderService {

	private static final Log logger = LogFactory.getLog(OrderService.class);

	@Autowired
	private JdbcTemplate jdbcTemplate;

	@Autowired
	private TransactionTemplate transactionTemplate;

	@Autowired
	private ApplicationEventPublisher applicationEventPublisher;

	public void addOrderByTransactionTemplate() {
		logger.info("addOrder 方法调用开始");
		long orderNo = System.currentTimeMillis();
		transactionTemplate.execute((status) -> {
			jdbcTemplate.update("insert into `order` (`order_no`,`price`) values(?,?)", orderNo, 5);
			return true;
		});
		logger.info("addOrder 方法调用结束");
	}

	@Transactional(rollbackFor = Exception.class)
	public void addOrder() {
		logger.info("addOrder 方法调用开始");
		long orderNo = System.currentTimeMillis();
		jdbcTemplate.update("insert into `order` (`order_no`,`price`) values(?,?)", orderNo, 5);

		// 1.通过 TransactionSynchronizationManager 监听事务状态
		TransactionSynchronizationManager.registerSynchronization(new TransactionSynchronizationAdapter() {
			@Override
			public void afterCompletion(int status) {
				if (STATUS_COMMITTED == status) {
					// 在事务提交后触发执行
					logger.info("事务状态：已提交");
				} else if (STATUS_ROLLED_BACK == status) {
					logger.info("事务状态：回滚");
				} else if (STATUS_UNKNOWN == status) {
					logger.info("事务状态：未知异常");
				} else {
					logger.info("事务状态：" + status);
				}
			}
		});

		// 2.通过 spring 事件， 监听事务状态
		applicationEventPublisher.publishEvent(new MyAfterTransactionEvent(orderNo));
		logger.info("addOrder 方法调用结束");
	}

}
